
$.fn.extend({
    tree:function(fnName,fnParam){
        if(!CommonUtils.isBlank(fnName)) {
            return treeFn[fnName].apply(this, [fnParam]);
        }
    }

});

var treeFn = {
    createInitOption:function(){
        var option={
            idField:undefined
            ,parentIdField:undefined
            ,textFormatter:null
            ,data:[]
            ,url:undefined
            ,method:undefined
            ,onClick:null
            ,stateField:undefined
        };
        return option;
    }
    ,getOption:function(){
        return $(this).data('tree-option');
    }
    ,init:function(option){
        var jq = $(this);
        //使用setTimeout进行异步处理
        setTimeout(function(){
            var treeNodes = null;
            if(!CommonUtils.isBlank(option.url) && CommonUtils.isBlank(option.data) ){
                option.data = ajaxGetData(option.url,option.method,option.param);
                treeNodes = changeToTreeNode(option.data,option);
            }else{
                //将数据转化为树形数据
                treeNodes = changeToTreeNode(option.data,option);
            }
            jq.data('tree-option',option);
            //生成树
            generatorTree.apply(jq,[treeNodes,option,0]);

            if(typeof option.onSuccessInit == 'function'){
                option.onSuccessInit.apply(jq);
            }
        },10);
    }
    ,refresh:function(){
        $(this).empty();
        var option = $(this).data('tree-option');
        if(option.url){
            option.data = null;
        }
        $(this).tree('init',option);
    }
};

function ajaxGetData(url,type,param){
    var result = null;
    $.ajax({
        url:url
        ,type:type
        ,data:param
        ,async:false
        ,success:function(data){
            result = data;
        }
        ,error:function(){

        }
    });
    return result;
}


function changeToTreeNode(array,option){
    var idField = option.idField;
    var parentIdField = option.parentIdField;
    var stateField = option.stateField;
    var textFormatter = option.textFormatter;


    if(CommonUtils.isBlank(array)){return null;}
    var result = [];
    var temp = {};
    array.forEach(function(item,index,arr){
        var node = {};
        var id = item[idField];
        temp[id] = node;
        node.id = id;
        node.parentId = item[parentIdField];
        if(typeof textFormatter == 'function'){
            node.text = textFormatter(item,index,arr);
        }else{
            node.text = node.id;
        }
        node.item = item;
        node.state = item[stateField];
        node.children = [];
        node.hasChildren = false;
    });
    $.each(temp,function (name,node) {
        var parent= temp[node.parentId];
        if(!CommonUtils.isBlank(parent)){
            parent.children.push(node);
            parent.hasChildren = true;
            return true;
        }
        result.push(node);
    });
    return result;
}

function generatorTree(treeArray,option,layer){
    this.addClass("tree list-group");
    //生成节点数组
    var lis = createTreeNodes.apply(this,[option,treeArray,layer]);
    var jq = this;
    lis.forEach(function(li){
        jq.append(li);
    });
}
function bindExpandTreeNode(iconjq,folderJq,expandUlJq,option){
    //当为文件类型的数据不绑定此展开事件
    if(folderJq.hasClass('icon-file')){
        return;
    }
    var li = this;
    iconjq.bind('click',function(){
        if(iconjq.hasClass('tree-expanded')){
            //关闭
            iconjq.removeClass('tree-expanded');
            iconjq.addClass('tree-collapsed');

            folderJq.removeClass('icon-folder-open');
            folderJq.addClass('icon-folder-close');

            expandUlJq.css('display','none');
        }else{
            //展开
            iconjq.removeClass('tree-collapsed');
            iconjq.addClass('tree-expanded');

            folderJq.removeClass('icon-folder-close');
            folderJq.addClass('icon-folder-open');

            expandUlJq.css('display','block');

            asyncLoadNode(li,expandUlJq,option);
        }
    });
}
function asyncLoadNode(li,expandUlJq,option){
    var node = li.data('tree-data');
    if(!node.hasChildren && !CommonUtils.isBlank(option.url)){
        var layer = li.data('tree-layer')+1;
        var loading = $('<li class="list-group-item"></li>');
        for(var i = 0; i< layer;i++){
            loading.append('<i class="treeIcon"></i>');
        }
        loading.append('<i class="tree-loading"></i>');
        expandUlJq.append(loading);
        setTimeout(function(){
            var data = ajaxGetData(option.url,option.method,{id:node.id});
            option.data = option.data.concat(data);
            var treeNodes = changeToTreeNode(data,option);
            expandUlJq.empty();
            if(CommonUtils.isBlank(treeNodes)){
                return;
            }
            node.hasChildren = true;
            node.children = treeNodes;
            generatorTree.apply(expandUlJq,[treeNodes,option,layer]);
        },10);
    }
}


function bindClickChangeCss(a){
    a.click(function(){
        $('.tree-text').parent().css({'background-color':'#fff'});
        $('.tree-text').css({'color':'#555'});

        a.parent().css({'background-color':'#FFCC99'});
        a.css({'color':'#555'});
    });
}


function createNode(option,node,index,array,layer){
    var jq = this;
    var li = $('<li class="list-group-item" id="treeNode_'+node.id+'" ></li>');
    li.data('tree-data',node);
    li.data('tree-layer',layer);

    var a = $('<span class="tree-text">'+node.text+'</span> ');
    var iconJq = $('<i class="treeIcon"></i>');
    var folderJq = $('<i class="iconfont"></i>');
    var ul = $('<ul class="list-group"></ul>');
    //CSS设置
    generatorNodeCss(node,iconJq,folderJq);

    //伸缩展开事件绑定
    bindExpandTreeNode.apply(li,[iconJq,folderJq,ul,option]);
    //点击节点样式改变事件绑定
    bindClickChangeCss(a);

    //递归调用
    if(node.hasChildren){
        var childrenLis = createTreeNodes.apply(jq,[option,node.children,layer+1]);
        childrenLis.forEach(function(item){
            ul.append(item);
        });
    }
    li.append(ul);
    li.prepend(a);
    li.prepend(folderJq);
    li.prepend(iconJq);
    for(var i = 0;i<layer;i++){
        li.prepend('<i class="treeIcon"></i>');
    }
    $.each(option,function(name,value){
        switch(name){
            case 'onClick':
                if(typeof value =='function'){
                    a.click(function(){
                        value(node,index,array);
                    });
                }
                break;
        }
    });
    return li;
}

function generatorNodeCss(node,iconJq,folderJq){
    switch(node.state){
        case 'closed':
            iconJq.addClass("tree-collapsed");
            folderJq.addClass("icon-folder-close");
            break;
        case 'open':
            iconJq.addClass("tree-expanded");
            folderJq.addClass("icon-folder-open");
            break;
        default:
            if(node.hasChildren){
                iconJq.addClass("tree-expanded");
                folderJq.addClass("icon-folder-open");
            }else{
                folderJq.addClass("icon-file");
            }
            break;
    }
}


function createTreeNodes(option,nodeArray,layer){
    var lis = [];
    var jq = this;
    nodeArray.forEach(function(node,index,array) {
        //生成单个节点
        var li = createNode.apply(jq,[option,node,index,array,layer]);
        if(li){
            lis.push(li);
        }
    });
    return lis;
}